package com.srwl.mytx.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.PayPasswordDialog;
import com.srwl.mytx.widget.RPTitleBar;
import com.srwl.mytx.widget.SecurityKeyBoardDialog;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by max on 16/2/26
 */
public class RetrievePayPasswordActivity extends BaseActivity {
    private static final String TAG = "RetrievePayPasswordActi";

    private RPTitleBar mTitleBar;
    private EditText et_password;
    private ImageView iv_hide;
    private ImageView iv_show;
    private Button btn_commit;
    private String password;
    private TextView tv_customer_service;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_retrieve_pay_password);
        initViewsAndEvents();
    }

    protected void initViewsAndEvents() {

        progressBar = findViewById(R.id.progress_bar);
        et_password = findViewById(R.id.et_password);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);
        btn_commit = findViewById(R.id.btn_commit);
        tv_customer_service = findViewById(R.id.tv_customer_service);

        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.INVISIBLE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.INVISIBLE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }

        });

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });

        tv_customer_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getCustomerServiceUserInfo();

            }
        });

    }

    void getCustomerServiceUserInfo() {
        if (!Helper.getInstance().isNetworkConnected()){
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customer_service, getString(R.string.system_busy));
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        startActivity(new Intent(RetrievePayPasswordActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, manualUser));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.INVISIBLE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customer_service, getString(R.string.system_busy));
                    }
                });
    }

    private void commit() {
        hideSoftKeyboard();
        password = et_password.getText().toString().trim();

        if (TextUtils.isEmpty(password)) {
            et_password.setHint("密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (password.length() < 6) {
            et_password.setTextColor(Color.RED);
            showToast(btn_commit, "密码不足6位");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        User updateUser = new User();
        updateUser.setPassword(password);
        checkPassword(updateUser);


    }

    private void checkPassword(final User updateUser) {
        if (!Helper.getInstance().isNetworkConnected()){
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .checkPassWord(updateUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_commit, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (result.getStatus() == Constant.PASS_WORD_WRONG) {
                                et_password.setTextColor(Color.RED);
                                if (result.getData() != null) {
                                    Integer remainRetryTime = (Integer) result.getData();
                                    if (remainRetryTime != 0) {
                                        if (!tv_customer_service.isShown()) {
                                            tv_customer_service.setVisibility(View.VISIBLE);
                                        }
                                        final ConfirmDialog dialog = new ConfirmDialog(RetrievePayPasswordActivity.this, "提示", "登录密码错误，还可以尝试" + remainRetryTime + "次");
                                        dialog.show();
                                    } else {
                                        if (!tv_customer_service.isShown()) {
                                            tv_customer_service.setVisibility(View.VISIBLE);
                                        }
                                        final ConfirmDialog dialog = new ConfirmDialog(RetrievePayPasswordActivity.this, "提示", "登录密码连续错误超过限制，再次错误将锁定账户");
//                                        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                                            @Override
//                                            public void confirm() {
//                                                startActivity(new Intent(RetrievePayPasswordActivity.this,ReplacePassWordActivity.class));
//                                            }
//                                        });
                                        dialog.show();
                                    }
                                }

                            } else if (result.getStatus() == Constant.FORBID_MODIFY_PAY_PASSWORD_24) {
                                if (!tv_customer_service.isShown()) {
                                    tv_customer_service.setVisibility(View.VISIBLE);
                                }
                                ConfirmDialog dialog = new ConfirmDialog(RetrievePayPasswordActivity.this, "提示", "该账户在24小时内修改过登录密码，为保护账户安全，禁止通过登录密码重置支付密码");
                                //不应该直接关闭，这时候用户可能需要联系客服
                                //dialog.setConfirmListener(() -> finish());
                                dialog.show();
                            } else if (result.getStatus() == Constant.RETRIEVE_PAY_PASSWORD_ERROR_LIMIT) {
                                if (!tv_customer_service.isShown()) {
                                    tv_customer_service.setVisibility(View.VISIBLE);
                                }
                                Integer expireMinutes = (Integer) result.getData();//限制 过期时间 单位： 分钟
                                ConfirmDialog dialog = new ConfirmDialog(RetrievePayPasswordActivity.this, "提示", expire(expireMinutes));
                                //不应该直接关闭，这时候用户可能需要联系客服
                                // dialog.setConfirmListener(() -> finish());
                                dialog.show();
                            }
                            return;
                        }

                        Log.d(TAG, "onResponse: 密码校验通过");
                        showKeyBoardDialog();


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.INVISIBLE);
                        showToast(btn_commit, getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    private void retrievePayPassword(final User updateUser) {
        if (!Helper.getInstance().isNetworkConnected()){
            this.showToast_v1(getString(R.string.network_anomalies));
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .replacePayPassword(updateUser)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.INVISIBLE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_commit, getString(R.string.system_busy));
                            return;
                        }


                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            return;
                        }

                        Log.d(TAG, "onResponse: 支付密码重置完成");
                        showKeyBoardDialog();
                        if (updateUser.getPayLimit() != null) {//如果免密支付额度被更改了，更新本地的免密支付额度
                            UserProfileManager.getInstance().setPayLimit(updateUser.getPayLimit());
                        }
                        ConfirmDialog dialog = new ConfirmDialog(RetrievePayPasswordActivity.this, "提示", "支付密码重置完成");
                        dialog.setConfirmListener(() -> finish());
                        dialog.show();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.INVISIBLE);
                        showToast(btn_commit, getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    void showKeyBoardDialog() {
        final Integer originalPayLimit = UserProfileManager.getInstance().getPayLimit();

        PayPasswordDialog payPasswordDialog = new PayPasswordDialog(this, SecurityKeyBoardDialog.TYPE_INPUT_NEW_PAY_PASSWORD, originalPayLimit);
        payPasswordDialog.setOnSetPasswordListener(new PayPasswordDialog.OnSetPassWordListener() {
            @Override
            public void onCommit(String payPassWord, int payLimit) {
                User updateUser = new User();
                updateUser.setPayPassword(payPassWord);
                if (payLimit != originalPayLimit) {
                    updateUser.setPayLimit(payLimit);
                }

                retrievePayPassword(updateUser);
            }
        });
        payPasswordDialog.show();


//        SecurityKeyBoardDialog keyBoardDialog = SecurityKeyBoardDialog.newInstance(SecurityKeyBoardDialog.TYPE_INPUT_NEW_PAY_PASSWORD, originalPayLimit);
//        keyBoardDialog.show(getSupportFragmentManager(), "retrieve_pay_password");
//        keyBoardDialog.setOnSetPasswordListener(new SecurityKeyBoardDialog.OnSetPassWordListener() {
//            @Override
//            public void onCommit(String payPassWord, int payLimit) {
//
//                User updateUser = new User();
//                updateUser.setPassword(password);
//                updateUser.setPayPassword(payPassWord);
//                if (payLimit != originalPayLimit) {
//                    updateUser.setPayLimit(payLimit);
//                }
//
//                replacePayPassword(updateUser);
//            }
//        });
    }


    private String expire(int expireTime) {
        int hours = expireTime / 60;
        int minutes = expireTime % 60;
        return String.format("输入的登录密码错误次数超过限制，为保护账户安全，还有%d 小时%d分钟后才能重试", hours, minutes);
    }

}
